<template>
  <el-card>
    <div class="chat-box" ref="chatBox">
      <div v-for="(msg, index) in messages" :key="index" class="message">
        <MessageBubble :msg="msg" :avatar="msg.type === 'user' ? avatar : avatar_bot" />
      </div>
    </div>
    <div class="input-area">
      <el-input
        v-model="input"
        placeholder="请输入您的问题..."
        @keyup.enter.native="sendMessage"
        class="input-field"
      ></el-input>
      <el-button type="primary" @click="sendMessage">发送</el-button>
    </div>
  </el-card>
</template>

<script>
import MessageBubble from './MessageBubble.vue'; // 提取消息气泡组件

export default {
  components: {
    MessageBubble,
  },
  data() {
    return {
      input: "",
      messages: [],
      avatar: require("@/assets/image/user.png"),
      avatar_bot: require("@/assets/image/bot.png"),
    };
  },
  methods: {
    async sendMessage() {
      const userInput = this.input.trim();
      if (!userInput) return;

      this.messages.push({ type: "user", content: userInput });
      this.input = "";
      this.loading = true;

      try {
        const response = await this.fetchResponse(userInput);
        this.messages.push({ type: "bot", content: response });
      } catch (error) {
        console.error('Error:', error);
        this.messages.push({ type: "bot", content: "发生错误，请重试。" });
      } finally {
        this.loading = false;
        this.scrollToBottom();
      }
    },
    async fetchResponse(userInput) {
      // 模拟 API 调用
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(`您说了: ${userInput}`);
        }, 1000);
      });
    },
    scrollToBottom() {
      this.$nextTick(() => {
        this.$refs.chatBox.scrollTop = this.$refs.chatBox.scrollHeight;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.chat-box {
  height: calc(100vh - 210px);
  overflow-y: auto;
  padding: 10px;
  border-radius: 8px;
  background-color: #f9f9f9; // 背景颜色
  border: 1px solid #e0e0e0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.input-area {
  display: flex;
  align-items: center;
  margin-top: 10px;
  background-color: #ffffff; // 输入区域背景
  border-radius: 8px;
  padding: 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.message {
  margin: 10px 0;
  display: flex;
  align-items: center;
}

.user-message-content,
.bot-message-content {
  max-width: 80%;
  padding: 10px;
  border-radius: 10px;
  margin: 5px 0;
  position: relative;
}

.user-message-content {
  background-color: #d1e7dd; // 用户消息背景
  align-self: flex-end; // 用户消息右对齐
}

.bot-message-content {
  background-color: #cfe2ff; // 机器人消息背景
  align-self: flex-start; // 机器人消息左对齐
}

.input-field {
  flex: 1;
  margin-right: 10px;
  max-width: calc(100% - 100px);
}

.el-button {
  background-color: #007bff; // 按钮背景颜色
  color: white; // 按钮文字颜色
  &:hover {
    background-color: #0056b3; // 悬停效果
  }
}
</style>
